import { Component, OnInit } from "@angular/core";
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router } from "@angular/router"; //路由引入

declare var $: any;
@Component({
  selector: "examine-staff",
  templateUrl: "./examine-staff.component.html",
  styleUrls: ["./examine-staff.css"],
})
export class ExamineStaffComponent implements OnInit {
  tableData: any = []; //table数据
  totalCount: number = 0; //分页总条数
  curPage: number = 1; //分页当前页
  pageSize: number = 10; //内置的分页每页条数
  editUserId: string = '';
  tableIndex: number = 0;
  allocationData: any = []; //审核分配内容数据
  userList: any = []; // 用户数据
  companyArrays: any = []; // 公司多选数组
  carListArrays: any = []; // 车型多选数组
  sensorSelect:any = ''; // 传感器多选
  editionList: any = []
  sensorList: any = []; // 传感器数据
  level: any = ''; // 权限类型
  range: any = []; // 权限类型内容数组
  isEditAllocation: boolean = false; // 是否是编辑
  isEditIndex: any = ''; // 要修改的allocationData下标
  isEditCreateTime: any = ''; // 暂存的allocationData修改时间
  rangeArr = []
  firmwareVs: any = '';
  constructor(private jsonApiService: JsonApiService, private router: Router) {}
  ngOnInit() {
    System.import('assets/js/bootstrap-switch.min.js').then(
			()=>{System.import('assets/css/bootstrap-switch.min.css').then(()=>{
				this.load();
			})
		});
    this.initAllUser();
    this.getSensorList();
  }
  //table刷新
  refresh() {
    this.load();
  }
  //初始化加载list数据  TODO
  load() {
		let that = this
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
    };
    this.jsonApiService.json_http("deviceInstallAuditor/queryAllDeviceInstallAuditor.html", data).subscribe((result) => {
      this.tableData = result.exhibitDatas || [];
      this.totalCount = result.recordCount;
      if(this.tableIndex || this.tableIndex == 0) {
        this.allocationData = this.tableData[this.tableIndex].auditInfoEntityList
      }
      System.import("assets/js/bootstrap-switch.min.js").then(() => {
        System.import("assets/css/bootstrap-switch.min.css").then(() => {
          setTimeout(function () {
            that.initSwitch();
          }, 1);
        });
      });
    });
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1;
    this.pageSize = e.rows;
    this.load();
  }
  // 添加
  addExamineStaff(modal) {
    $('#useIdSelect').val('');
    $('#useIdSelect').val('').trigger('change');
    modal.show();
  }
  //初始化开关
  initSwitch() {
    var that = this;
    $(".isEnable").bootstrapSwitch({
      //初始化按钮
      onText: "开启",
      offText: "停用",
      onColor: "primary",
      offColor: "warning",
      onSwitchChange: function (event, state) {
        if (state == true) {
          that.checkStatus("1", event.target.id);
        } else {
          that.checkStatus("0", event.target.id);
        }
      },
    });
  }
  //是否启用
  checkStatus(check, id) {
    this.jsonApiService.http_get(`deviceInstallAuditor/updateIsEnable.html?userId=${id}&isEnable=${check}`).subscribe((data) => {
      if (data.success) {
        this.load();
      } else {
        this.jsonApiService.message(data.message);
      }
    });
  }
  examineAllocation(row, modal, index) {
    this.tableIndex = index;
    this.editUserId = row.userId;
    this.allocationData = this.tableData[index].auditInfoEntityList;
    System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
      System.import('assets/js/select2-zh-CN.js').then(()=>{
        this.initAllSelect3();
      })
    })
    modal.show();
  }
  // 删除
  examineDelete(row) {
    this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
			this.jsonApiService.http_get(`deviceInstallAuditor/delDeviceInstallAuditor.html?userId=${row.userId}`).subscribe(result => {
				this.jsonApiService.message(result.message);
				this.load();
			})
		})
  }
  // 新增审核人员
  userNameSubmit(modal) {
    let userId = $('#useIdSelect').val();
    if (userId) {
      let userData = this.userList.filter(item => item.id == userId)
      let data = {
        userId: userData[0].id,
        userName: userData[0].name
      }
      this.jsonApiService.json_http("deviceInstallAuditor/addDeviceInstallAuditor.html", data).subscribe((result) => {
        if (result.success) {
          modal.hide();
          this.load();
        } else {
          this.jsonApiService.message(result.message);
        }
      });
    }else {
      this.jsonApiService.message('请选择账户');
    }
  }
  userNameClose(modal) {
    modal.hide();
  }
  userNameChange(val) {
    console.log(val)
  }
  levelChange(val) {
    this.editionList = [];
    this.sensorSelect = '';
    $('#sensorSelect2').val('');
    $('#sensorSelect2').select2();
		$('#sensorInput').val('');
    this.companyArrays = [];
    this.carListArrays = [];
  }
  //拉取
	initAllUser() {
    this.jsonApiService.http("user/queryAllUser.html", null).subscribe((data) => {
      if (data.success) {
        this.userList = data.data;
        $('#select2-useIdSelect-container').css('line-height', '34px');
      }
    });
	}
  // 审核内容分配
  addAllocation(modal) {
    this.isEditAllocation = false
    this.level = '';
    this.editionList = [];
    this.sensorSelect = '';
    $('#sensorSelect2').val('');
    $('#sensorSelect2').select2();
		$('#sensorInput').val('');
    modal.show();
  }
  // 编辑审核内容分配
  editAllocation(modal, row, index) {
    this.level = row.level;
    let companySelectedList = []
    console.log(row)
    if(row.level == 2) {
      for(let i = 0; i < row.range.length; i++){
        let obj = {
          companyName: row.range[i].text,
          companyId: row.range[i].id
        }
        companySelectedList.push(obj)
      }
      this.companyArrays = companySelectedList
    }else if(row.level == 3) {
      this.carListArrays = row.range
    }else if(row.level == 4) {
      this.editionList = row.range;
    }else if(row.level == 5) {
      let sensorSelect = []
      for(let i = 0; i < row.range.length; i++){
        sensorSelect.push(row.range[i].id)
      }
      this.sensorSelect = sensorSelect.join(',');
      $('#sensorSelect2').val(sensorSelect).trigger('change');
    }
    this.isEditAllocation = true;
    this.isEditIndex = index;
    this.isEditCreateTime = row.createTime;
    modal.show();
  }
  // 删除审核内容
  deleteAllocation(row, index) {
    this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(()=>{
      this.allocationData.splice(index, 1)
			this.jsonApiService.json_http(`deviceInstallAuditor/updateAudit.html?userId=${this.editUserId}`, this.allocationData).subscribe(result => {
				this.jsonApiService.message(result.message);
				this.load();
			})
		})
  }
  // 添加-编辑审核内容权限
  staffPowerSubmit(modal) {
    if(!this.level){
      this.jsonApiService.message('请选择权限类型');
      return;
    }
    if(this.level == 1){
      this.range = null
    }else if(this.level == 4){
      if(this.editionList.length){
        this.range = this.editionList
      }else {
        this.jsonApiService.message('请选择固件');
        return;
      }
    }else if(this.level == 5){
      let sensorSelect = this.getSelect2Value('#sensorSelect2');
      if(sensorSelect.length){
        let range = [];
        let sensorArray = sensorSelect.split(',');
        for(let i = 0; i < sensorArray.length; i++){
          let obj = this.sensorList.filter(item => item.id == sensorArray[i])
          range.push(obj[0])
        }
        this.range = range
      }else {
        this.jsonApiService.message('请选择传感器');
        return;
      }
    }
    if(this.level == 2 && !this.range.length){
      this.jsonApiService.message('请选择公司');
      return;
    }
    if(this.level == 3){
      this.range = this.rangeArr
      if(!this.range.length) {
        this.jsonApiService.message('请选择车型');
        return;
      }
    }
    let data:any = {
      level: this.level,
      range: this.range
    }
    if(this.isEditAllocation) {
      data.createTime = this.isEditCreateTime;
      this.allocationData[this.isEditIndex] = data;
      this.jsonApiService.json_http(`deviceInstallAuditor/updateAudit.html?userId=${this.editUserId}`, this.allocationData).subscribe((result) => {
        modal.hide();
        this.load();
        this.isEditAllocation = false
        this.jsonApiService.message(result.message);
      });
    }else {
      let levelState = this.allocationData?this.allocationData.some(item => item.level == data.level):false;
      if(levelState) {
        this.jsonApiService.message('已存在该权限类型');
        return;
      }
      this.jsonApiService.json_http(`deviceInstallAuditor/addAudit.html?userId=${this.editUserId}`, data).subscribe((result) => {
        modal.hide();
        this.load();
        this.jsonApiService.message(result.message);
      });
    }
  }
  staffPowerClose(modal) {
    this.isEditAllocation = false
    modal.hide();
  }
  // 公司多选返回
  addCompanySelected(data) {
    this.companyArrays = data.companySelectedList
    let range = [];
    for(let i = 0; i < data.companySelectedList.length; i++){
      let obj = {
        text: data.companySelectedList[i].companyName,
        id: data.companySelectedList[i].companyId
      }
      range.push(obj);
    }
    this.range = range;
  }
  selectedValue(data) {
    this.rangeArr = data.selectedList;
    this.range = data.selectedList;
  }

  initAllSelect3(){
		var that = this;
		$("#sensorSelect2").select2({
      language : "zh-CN",
      data: this.sensorList
    }).on("select2:select", function (e){
      var data = e.params.data;
			$("#sensorInput").val(data.text).change();
			that.sensorSelect = data.text;
    });
	}
	getSelect2Value(id){
		var data = $(id).select2("data");
		var result = '';
		for(let item of data){
			result += item.id+",";
		}
		result = result.substring(0,result.length-1);
		return result;
	}
  // 获取传感器
  getSensorList() {
    this.jsonApiService.http('sensorManage/querySensorList.html','').subscribe(data=> {
      if(data.success){
        let sensorList = []
        for(let i = 0; i < data.data.length; i++){
          let obj = {
            text : data.data[i].sensorName,
            id : data.data[i].id
          }
          sensorList.push(obj)
        }
        this.sensorList = sensorList
      }
    })
  }
  // 添加固件版本号
  addFirmwareVs() {
    this.firmwareVs = this.firmwareVs.replace(/(^\s*)|(\s*$)/g, "");
    if(this.firmwareVs) {
      let obj = {
        text: this.firmwareVs,
        id: this.RndNum(2)
      }
      this.editionList.push(obj);
      this.firmwareVs = '';
    }else {
      this.jsonApiService.message('请输入固件版本号');
    }
  }
  removeEditionList(index) {
    this.editionList.splice(index, 1);
  }
  RndNum(n){
    var rnd="";
    for(var i=0;i<n;i++){
      rnd+=Math.floor(Math.random()*10);
    }
    return rnd;
  }
}
